package com.eorchis.util;

import java.io.OutputStream;
import java.io.Writer;
import java.util.regex.Pattern;

import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Result;

public class XMLStreamWriterForCDATA extends XMLStreamWriterDelegate {

	private static final Pattern XML_CHARS = Pattern.compile("[&<>]");
	private static final Pattern CDATA_ENDSWITH = Pattern.compile("\\]\\]\\>");
	private static final String CDATA_ENDSWITH_REPLACE = "]]]]><![CDATA[";

	public XMLStreamWriterForCDATA(Writer stream) {
		super(stream);
	}

	public XMLStreamWriterForCDATA(OutputStream stream) {
		super(stream);
	}

	public XMLStreamWriterForCDATA(OutputStream stream, String encoding) {
		super(stream, encoding);
	}

	public XMLStreamWriterForCDATA(Result result) {
		super(result);
	}

	public void writeCharacters(String text) throws XMLStreamException {
		boolean useCData = XML_CHARS.matcher(text).find();
		if (useCData) {
			text = CDATA_ENDSWITH.matcher(text).replaceAll(CDATA_ENDSWITH_REPLACE);
			super.writeCData(text);
		} else {
			super.writeCharacters(text);
		}
	}
}
